//
//  ResultProtocol.swift
//  Employee
//
//  Created by swordjoy on 2017/4/1.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import Foundation
import SwiftyJSON
import Result
import Moya

var LoginSuccessResponseCode = "1003"
var UsernameOrPasswordErrorResponseCode = "1016"
var Token_Invalid_Error = "1018"
var Data_Operate_Success = "1001"
var Other_Device_Login = "1019"

var UsernameOrPasswordError_Hint = "账号或密码错误"
var LoginFailure_Hint = "登录失败"

protocol LoginResultProtocol {
  
  func loginProtocol(with result: Result<Response, MoyaError>, loginSuccess: ((_ data: JSON) -> Void), loginFailure: VoidClosure?)
  
}

extension LoginResultProtocol {
  
  func loginProtocol(with result: Result<Response, MoyaError>, loginSuccess: ((_ data: JSON) -> Void), loginFailure: VoidClosure?) {
    switch result {
    case let .success(response):
        
      let json = JSON(data: response.data)
      let responseCode = json["responseCode"].stringValue
      
      // 这里用来判断单点登录
      if let urlResponse = response.response  {
        
        if let cookie = HTTPCookie.cookies(withResponseHeaderFields: urlResponse.allHeaderFields as! [String : String], for: response.response!.url!).first {
             Cookie.cacheCookie(cookie: "\(cookie.name)=\(cookie.value)")
        }
    
      }
      
      // 登录成功
      if LoginSuccessResponseCode == responseCode {
        loginSuccess(json["data"])
        return
      }
      loginFailure?()
      
      // 账号密码错误
      if UsernameOrPasswordErrorResponseCode == responseCode {
        SJHint.show(UsernameOrPasswordError_Hint)
        return
      }
      
      // 返回为空,服务器错误
      if "" == responseCode {
        SJHint.show("服务器错误")
        return
      }
      
      SJHint.show(LoginFailure_Hint)
    case let .failure(error):
        loginFailure?()
      runOnMainThread {
        if error.errorDescription == "请求超时。" {
          SJHint.show("请求超时")
        } else {
          SJHint.show("登录失败")
        }
      }

    }
    
  }
  
}

protocol DataResultProtocol {
  
  func dataProtocol(with result: Result<Response, MoyaError>, isHideHUD: Bool, success: ((_ data: JSON) -> Void), failure: VoidClosure?)
  
  func dataProtocol(with result: Result<Response, MoyaError>, isHideHUD: Bool, success: ((_ data: JSON) -> Void), overdue: @escaping VoidClosure , failure: VoidClosure?)
  
}

extension DataResultProtocol {
  
    func dataProtocol(with result: Result<Response, MoyaError>, isHideHUD: Bool = true, success: ((_ data: JSON) -> Void), failure: VoidClosure?) {
    
    switch result {
    case let .success(response):
        if isHideHUD {
            // 隐藏hud
            runOnMainThread {
                SJApp.hideHUD()
                SJApp.hideStateBarHUD()
            }
        }
        
      let json = JSON(data: response.data)
      let responseCode = json["responseCode"].stringValue
      
      // 成功
      if Data_Operate_Success == responseCode {
        success(json["data"])
        return
      }
        
      failure?()
      
      // 如果是其他设备登录
        if Other_Device_Login == responseCode {
            User.logoutClean()
            User.otherDeviceLogin()
            return
        }
      
        if "" == responseCode {
            SJHint.show("服务器错误")
            return
        }
      
      // 错误提示服务器的信息
      SJHint.show(json["message"].stringValue)

    case let .failure(error):
        failure?()
      runOnMainThread {
        SJApp.hideHUD()
        SJApp.hideStateBarHUD()
        if error.errorDescription == "请求超时。" {
          SJHint.show("请求超时")
        }
      }
      
    }
    
  }
  
  func dataProtocol(with result: Result<Response, MoyaError>, isHideHUD: Bool = true, success: ((_ data: JSON) -> Void), overdue: @escaping VoidClosure, failure: VoidClosure?) {
    switch result {
    case let .success(response):
        if isHideHUD {
            runOnMainThread {
                SJApp.hideHUD()
                SJApp.hideStateBarHUD()
            }
        }
        
        
      let json = JSON(data: response.data)
      let responseCode = json["responseCode"].stringValue
    
      if Data_Operate_Success == responseCode {
        success(json["data"])
        return
      }
      failure?()
      
      // 如果是其他设备登录
      if Other_Device_Login == responseCode {
        User.logoutClean()
        User.otherDeviceLogin()
        return
      }
      
      // token 过期
      if Token_Invalid_Error == responseCode {
        let _ = UserRequest.shared.refreshToken { overdue() }
        return
      }

      if "" == responseCode {
        SJHint.show("服务器错误")
        return
      }
      
      // 错误提示服务器的信息
      SJHint.show(json["message"].stringValue)
      
    case let .failure(error):
        failure?()
      runOnMainThread {
        SJApp.hideHUD()
        SJApp.hideStateBarHUD()
        if error.errorDescription == "请求超时。" { SJHint.show("请求超时") }
      }
    }
    
  }
  
}

